import logging
import pickle
import re
import uuid
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed

logger = logging.getLogger(__name__)

from PySide6.QtCore import QThread, Signal

class AINameMatcher(QThread):
    result = Signal(bytes)
    target_columns = [
        "最小电压",
        "最小电压节数",
        "最大电压",
        "最大电压节数",
        "最小温度",
        "最小温度节数",
        "最大温度",
        "最大温度节数",
        "SOC"
    ]

    def __init__(self, parent=None):
        super().__init__(parent)
        self.from_columns = []
        
    def set_from_columns(self, from_columns):
        self.from_columns = from_columns

    def get_token(self):
        """获取认证token"""
        url = "http://10.62.170.202:54246/get_token"
        try:
            res = requests.get(url, timeout=10)
            return res.json().get('token', '')
        except Exception as e:
            logger.error(f"获取token失败: {e}")
            return ""

    def extract_column_name(self, data):
        """
        从AI模型的响应中提取列名
        """
        try:
            msg_content = data.get('msg', '')
            # 使用正则表达式提取最终列名（位于标签之后）
            match = re.search(r'\s*(\S+)', msg_content)
            if match:
                return match.group(1)

            # 如果正则匹配失败，尝试直接提取最后一部分非空内容
            parts = msg_content.split()
            if parts:
                return parts[-1]
        except Exception as e:
            logger.error(f"解析AI响应失败: {e}")
        return ""

    def ai_match_column(self, target_description):
        """
        使用AI接口匹配单个目标列的列名
        """
        url = "https://ai.fdbatt.com/prod-ui/chat/sendMsg"
        token = self.get_token()
        if not token:
            logger.error("无法获取认证token")
            return None
            
        headers = {"Authorization": f"Bearer {token}"}
        
        # 构建查询消息 - 使用制表符分隔列名
        columns_str = "\t".join(self.from_columns)
        msg = f'从下面这些列名中找出最可能代表"{target_description}"的列名(一般是英文)(只输出列名，不要解释)：{columns_str}'
        
        body = {
            "modelId": "deepseek-r1-chat",
            "msg": msg,
            "sessionId": str(uuid.uuid4())[:10]
        }
        
        try:
            res = requests.post(url=url, headers=headers, data=body, timeout=60)
            if res.status_code == 200:
                target = self.extract_column_name(res.json())
                return target
            else:
                logger.error(f"AI接口请求失败，状态码: {res.status_code}")
                return None
        except Exception as e:
            logger.error(f"请求AI接口时发生错误: {e}")
            return None

    def run(self):
        signals = []

        # 使用线程池并发请求AI接口
        with ThreadPoolExecutor(max_workers=3) as executor:  # 限制并发数为3，避免过多请求
            # 创建任务字典 {future: target_column}
            future_to_target = {
                executor.submit(self.ai_match_column, target): target 
                for target in self.target_columns
            }
            
            # 等待所有任务完成并收集结果
            for future in as_completed(future_to_target):
                target = future_to_target[future]
                try:
                    result = future.result()
                    logger.info(f"匹配结果: {target} -> {result}")
                except Exception as e:
                    logger.error(f"处理{target}时发生错误: {e}")
                    result = ""
                signals.append(result)
        # 发送结果
        self.result.emit(pickle.dumps(signals))
